package cn.exrick.service.impl;

import cn.exrick.common.exception.XmallException;
import cn.exrick.mapper.TbMemberMapper;
import cn.exrick.mapper.TbQuestionCatMapper;
import cn.exrick.mapper.TbQuestionCommentMapper;
import cn.exrick.mapper.TbQuestionMapper;
import cn.exrick.pojo.TbMember;
import cn.exrick.pojo.TbQuestion;
import cn.exrick.pojo.TbQuestionCat;
import cn.exrick.pojo.TbQuestionComment;
import cn.exrick.pojo.TbQuestionCommentExample;
import cn.exrick.pojo.TbQuestionExample;
import cn.exrick.pojo.common.DataTablesResult;
import cn.exrick.pojo.front.QuestionCommentResult;
import cn.exrick.pojo.front.QuestionResult;
import cn.exrick.service.QuestionService;
import cn.exrick.utils.mybatis.Page;
import cn.exrick.utils.mybatis.PageParam;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Description:
 */
@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private TbQuestionMapper tbQuestionMapper;
    @Autowired
    private TbQuestionCatMapper tbQuestionCatMapper;
    @Autowired
    private TbMemberMapper tbMemberMapper;
    @Autowired
    private TbQuestionCommentMapper tbQuestionCommentMapper;

    @Override
    public DataTablesResult getQuestionPage(int draw, int start, int length, String search, Long catId,
                                            String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();

        //分页执行查询返回结果
        PageHelper.startPage(start / length + 1, length);
        PageHelper.orderBy(orderCol + " " + orderDir);
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("search", search);
        if(null != catId){
            paramsMap.put("catId", catId);
        }
        paramsMap.put("minDate", minDate);
        paramsMap.put("maxDate", maxDate);

        List<TbQuestion> list = tbQuestionMapper.selectByPage(paramsMap);
        PageInfo<TbQuestion> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int) pageInfo.getTotal());
        result.setRecordsTotal((int) pageInfo.getTotal());

        result.setDraw(draw);
        result.setData(list);

        return result;
    }

    @Override
    public int save(TbQuestion tbQuestion) {
        TbQuestionCat tbQuestionCat = tbQuestionCatMapper.selectByPrimaryKey(tbQuestion.getCatId());
        if(null == tbQuestionCat){
            throw new XmallException("问答分类不存在");
        }
        int result = tbQuestionMapper.insertSelective(tbQuestion);
        if(1 != result){
            throw new XmallException("提交问答失败");
        }
        return result;
    }

    @Override
    public int updateStatus(Long id) {
        TbQuestion tbQuestion = tbQuestionMapper.selectByPrimaryKey(id);
        if(null == tbQuestion){
            throw new XmallException("问答不存在");
        }
        if(tbQuestion.getStatus() == 0){
            tbQuestion.setStatus(1);
        } else {
            tbQuestion.setStatus(0);
        }
        int result = tbQuestionMapper.updateByPrimaryKeySelective(tbQuestion);
        if(1 != result){
            throw new XmallException("显示/隐藏失败");
        }
        return 1;
    }

    @Override
    public Page<QuestionResult> getQuestionPageForApi(int currentPage, int size, Long memberId, Integer type, Long category, String search) {
        // 分页
        if (currentPage <= 0) {
            currentPage = 1;
        }
        PageHelper.startPage(currentPage, size);
        PageHelper.orderBy("created desc");
        PageParam pageParam = new PageParam(currentPage - 1, size);
        Page<QuestionResult> page = new Page<QuestionResult>(pageParam);
        List<QuestionResult> list = new ArrayList<>();

        TbQuestionExample example = new TbQuestionExample();
        TbQuestionExample.Criteria criteria = example.createCriteria();
        // 查询显示状态的记录
        criteria.andStatusEqualTo(0);
        if(null != category){
            criteria.andCatIdEqualTo(category);
        }

        if(StringUtils.isNotBlank(search)){
            criteria.andContentLike("%" + search + "%");
        }

        List<TbQuestion> tbQuestions;
        if(null == type){
            tbQuestions = tbQuestionMapper.selectByExample(example);
        }else if(type == 0){
            // 查询我发布过的
            criteria.andMemberIdEqualTo(memberId);
            tbQuestions = tbQuestionMapper.selectByExample(example);
        }else if(type == 1){
            // 查询我评论过的
            TbQuestionCommentExample questionCommentExample = new TbQuestionCommentExample();
            questionCommentExample.createCriteria().andMemberIdEqualTo(memberId);
            List<TbQuestionComment> comments = tbQuestionCommentMapper.selectByExample(questionCommentExample);
            Set<Long> questionIds = new HashSet<>();
            for (TbQuestionComment comment : comments){
                questionIds.add(comment.getQuestionId());
            }
            if(questionIds.size() > 0){
                criteria.andIdIn(new ArrayList<>(questionIds));
                tbQuestions = tbQuestionMapper.selectByExample(example);
            }else{
                tbQuestions = new ArrayList<>();
            }
        }else{
            tbQuestions = new ArrayList<>();
        }

        for (TbQuestion tbQuestion : tbQuestions){
            list.add(getQuestionResult(tbQuestion));
        }

        PageInfo<TbQuestion> pageInfo = new PageInfo<>(tbQuestions);
        page.setTotalCount((int) pageInfo.getTotal());
        page.setResult(list);

        return page;
    }

    @Override
    public QuestionResult getDetailForApi(Long questionId) {
        TbQuestion tbQuestion = tbQuestionMapper.selectByPrimaryKey(questionId);
        if(null != tbQuestion){
            return getQuestionResult(tbQuestion);
        }
        return null;
    }

    @Override
    public int saveComment(Long memberId, Long questionId, String content) {
        TbQuestionComment tbQuestionComment = new TbQuestionComment();
        tbQuestionComment.setQuestionId(questionId);
        tbQuestionComment.setMemberId(memberId);
        tbQuestionComment.setContent(content);
        tbQuestionComment.setCreated(new Date());
        return tbQuestionCommentMapper.insertSelective(tbQuestionComment);
    }

    @Override
    public Page<QuestionCommentResult> getQuestionCommentPageForApi(int currentPage, int size, Long questionId) {
        // 分页
        if (currentPage <= 0) {
            currentPage = 1;
        }
        PageHelper.startPage(currentPage, size);
        PageHelper.orderBy("created desc");
        PageParam pageParam = new PageParam(currentPage - 1, size);
        Page<QuestionCommentResult> page = new Page<QuestionCommentResult>(pageParam);
        List<QuestionCommentResult> list = new ArrayList<>();

        TbQuestionCommentExample example = new TbQuestionCommentExample();
        TbQuestionCommentExample.Criteria criteria = example.createCriteria();
        criteria.andQuestionIdEqualTo(questionId);
        criteria.andStatusEqualTo(0);

        List<TbQuestionComment> comments = tbQuestionCommentMapper.selectByExample(example);
        QuestionCommentResult result;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (TbQuestionComment comment : comments){
            result = new QuestionCommentResult();
            result.setContent(comment.getContent());
            result.setCreateDate(formatter.format(comment.getCreated()));

            // 查询用户信息
            TbMember tbMember = tbMemberMapper.selectByPrimaryKey(comment.getMemberId());
            if(null != tbMember){
                result.setMemberId(tbMember.getId());
                result.setMemberName(tbMember.getUsername());
                result.setMemberAvatar(tbMember.getFile());
            }

            list.add(result);
        }

        PageInfo<TbQuestionComment> pageInfo = new PageInfo<>(comments);
        page.setTotalCount((int) pageInfo.getTotal());
        page.setResult(list);

        return page;
    }

    private QuestionResult getQuestionResult(TbQuestion tbQuestion){
        QuestionResult result = new QuestionResult();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        result.setQuestionId(tbQuestion.getId());
        result.setTitle(tbQuestion.getTitle());
        result.setContent(tbQuestion.getContent());
        result.setUrl("/dist/index.html#/questionId=" + tbQuestion.getId());
        result.setImage(tbQuestion.getImage());
        result.setCreateDate(formatter.format(tbQuestion.getCreated()));

        // 查询用户信息
        TbMember tbMember = tbMemberMapper.selectByPrimaryKey(tbQuestion.getMemberId());
        if(null != tbMember){
            result.setMemberId(tbMember.getId());
            result.setMemberName(tbMember.getUsername());
            result.setMemberAvatar(tbMember.getFile());
        }

        // 查询评论数量
        TbQuestionCommentExample example = new TbQuestionCommentExample();
        example.createCriteria().andQuestionIdEqualTo(tbQuestion.getId()).andStatusEqualTo(0);
        int count = tbQuestionCommentMapper.countByExample(example);
        result.setCommentCount(count);

        return result;
    }

}
